package jys.test.yddata;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.ImageCapture;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Size;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;


import jys.test.yddata.pictureselector.PictureBean;
import jys.test.yddata.pictureselector.PictureSelector;
import jys.test.yddata.ui.LabelTable;
import jys.test.yddata.ui.SquareRelativeLayout;
import jys.test.yddata.ui.ToolbarPlus;
import jys.test.yddata.utils.CameraManager;
import jys.test.yddata.utils.ClientManager;
import jys.test.yddata.utils.PropertiesUtil;

public class MainActivity extends AppCompatActivity {
    private Button captureBt;
    private ToolbarPlus mToolbar;
    private LabelTable label_table;
    private View loadingView, okView, noView, camera_view;
    private SquareRelativeLayout squareView;

    public static int windows_w, windows_h, labels_height;

    private CameraManager cameraManager;
    private ClientManager clientManager;

    private PropertiesUtil projectProp;

    private boolean onError = false, showLabel = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadingView = findViewById(R.id.loading);
        okView = findViewById(R.id.ok);
        noView = findViewById(R.id.no);
        camera_view = findViewById(R.id.camera_view);
        captureBt = findViewById(R.id.capture);
        mToolbar = findViewById(R.id.settingBar);
        squareView = findViewById(R.id.squareRelativeLayout);

        try {
            projectProp = PropertiesUtil.buildFromDisk(this, "project");
        } catch (IOException e) {
            e.printStackTrace();
            seriousError("配置加载出错，Exp ["+e.getMessage()+"]");
        }

        try { initView(); } catch (Exception e) {
            e.printStackTrace();
            seriousError("视图加载出错，Exp ["+e.getMessage()+"]");
        }

        try { initManage(); } catch (Exception e) {
            e.printStackTrace();
            seriousError("管理加载出错，Exp ["+e.getMessage()+"]");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkVerify();
        try { resumeView(); } catch (Exception e) {
            e.printStackTrace();
            seriousError("视图渲染出错，Exp ["+e.getMessage()+"]");
        }
    }

    public void initView() {
        // 加载 Toolbar
        mToolbar.settingTitle(projectProp.getProperty("server.dataSet.name"))
                .settingLeft(R.drawable.ic_upload, this::jump2Upload)
                .settingRight(R.drawable.ic_setting, this::jump2Setting);
        setSupportActionBar(mToolbar);

        // 加载标签阵列
        label_table = findViewById(R.id.label_table);
        label_table.post(()->label_table.addLabels(3,
                projectProp.getProperty("label.default"),
                Arrays.asList(projectProp.getProperty("label.list").split(","))
        ));

        // 动态宽高
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        windows_w = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
        windows_h = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight()-statusBarHeight1;

        labels_height = (projectProp.getProperty("label.list").split(",").length+2)/3*500/3;
        squareView.setWH(
                windows_w, windows_h-130-200-50-labels_height,
                projectProp.getIntProperty("photo.width"),
                projectProp.getIntProperty("photo.height"));

        label_table.setHeight(labels_height);
    }

    public void resumeView() {
        // 加载九宫格
        findViewById(R.id.drawT9View).setVisibility(
                projectProp.getBooleanProperty("view.showT9") ? View.VISIBLE : View.GONE
        );

        // 加载水平仪
        findViewById(R.id.drawLevelView).setVisibility(
                projectProp.getBooleanProperty("view.showLevel") ? View.VISIBLE : View.GONE
        );
    }

    public void initManage() {
        // 加载相机预览及拍照功能
        camera_view.post(()-> cameraManager = new CameraManager.Builder()
                .init(this,
                        findViewById(R.id.camera_view),
                        new Size(projectProp.getIntProperty("photo.width"),
                                projectProp.getIntProperty("photo.height")),
                        this::seriousError)
                .initCapture(captureBt,
                        this::startLoading,
                        this::sendFig,
                        this::endLoading_Capture)
                .build());

        // 加载服务器配置及发送功能
        clientManager = new ClientManager.Builder()
                .init(this,
                        this::endLoading_Client,
                        projectProp.getProperty("server.url"))
                .addBaseKey("datasetId", projectProp.getProperty("server.dataSet.id"))
                .addBaseKey("width", projectProp.getProperty("photo.width"))
                .addBaseKey("height", projectProp.getProperty("photo.height"))
                .build();
    }

    public void checkVerify() {
        captureBt.setEnabled(false);
        if (onError) return;
        if (projectProp.getProperty("server.verify", "0").equals("0"))
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("未加载数据集配置，请在设置界面更换数据集")
                    .setPositiveButton("跳转至设置", (dialog, which)-> jump2Setting(null))
                    .show();
        else
            captureBt.setEnabled(true);
    }

    public void seriousError(String message) {
        onError = true;
        new AlertDialog.Builder(this)
                .setTitle("错误")
                .setMessage(message)
                .setPositiveButton("退出", (dialog, which)-> finish())
                .show();
    }

    public void jump2Upload(View v) {
        PictureSelector
                .create(MainActivity.this, PictureSelector.SELECT_REQUEST_CODE)
                .selectPicture(true,
                        projectProp.getIntProperty("photo.width"),
                        projectProp.getIntProperty("photo.height"),
                        projectProp.getIntProperty("photo.width"),
                        projectProp.getIntProperty("photo.height"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                String figpath = clientManager.getFigFromExt(pictureBean.getPath());

                final Spinner labelSpinner = new Spinner(this);
                ArrayAdapter<String> arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, projectProp.getProperty("label.list").split(","));
                arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                labelSpinner.setAdapter(arr_adapter);
                labelSpinner.setPadding(50, 50, 50, 50);

                new AlertDialog.Builder(this)
                        .setTitle("标签选择")
                        .setView(labelSpinner)
                        .setPositiveButton("确认", (dialog, which)->{
                            startLoading();
                            clientManager.sendFigLabel(
                                    figpath,
                                    (String) labelSpinner.getSelectedItem()
                            );
                        })
                        .setNegativeButton("取消", (dialog, which)->{})
                        .show();
            } else {
                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("上传失败")
                        .setPositiveButton("确定", (dialog, which)-> {})
                        .show();
            }
        } else if (requestCode == 1024) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "存储权限获取成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "请手动打开该应用需要的权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void jump2Setting(View v) {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

    public void showLabelBt(View v) {
        showLabel = !showLabel;

        // 改变按钮图标
        Drawable drawable=getResources().getDrawable(showLabel?R.drawable.ic_down:R.drawable.ic_up);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        ((Button) v).setCompoundDrawables(null, drawable, null,null);

        // 改变LabelView纵横比
        squareView.setWH(
                windows_w, windows_h-130-200-50-(showLabel?labels_height:1),
                projectProp.getIntProperty("photo.width"),
                projectProp.getIntProperty("photo.height"));
        label_table.setHeight(showLabel?labels_height:1);
    }

    public void sendFig(ImageCapture.OutputFileResults outputFileResults) {
        clientManager.sendFigLabel(
                Objects.requireNonNull(outputFileResults.getSavedUri()).getPath(),
                label_table.getLabel()
        );
    }

    public boolean startLoading() {
        loadingView.setVisibility(View.VISIBLE);
        label_table.setEnabled(false);
        captureBt.setEnabled(false);
        captureBt.setText("处 理 中 ...");
        return true;
    }

    public void endLoading_Capture(boolean isOK) {
        if (!isOK) {
            loadingView.setVisibility(View.GONE);
            label_table.setEnabled(true);
            captureBt.setEnabled(true);
            captureBt.setText("拍 照 并 上 传");
            noView.setVisibility(View.VISIBLE);
        } else if (captureBt.getText().equals("处 理 中 ...")) {
            captureBt.setText("上 传 中 ...");
        }
    }

    public void endLoading_Client(boolean isOK) {
        loadingView.setVisibility(View.GONE);
        label_table.setEnabled(true);
        captureBt.setEnabled(true);
        captureBt.setText("拍 照 并 上 传");
        if (isOK) okView.setVisibility(View.VISIBLE);
        else noView.setVisibility(View.VISIBLE);
    }
}
